/**
 * Unified request results middleware
 * @param option Contains type, success failure/return code, return information
 * @returns
 */
function routerResponse(
  option = { type: 'json', successCode: "000000", failCode: 999999, successMsg: '失败' }
) {
  return async function (ctx: any, next: any) {
    ctx.append("Access-Control-Allow-Origin", "*");

    ctx.success = function (data: any, msg: any) {
      ctx.type = option.type;
      ctx.body = {
        status: "success",
        code: option.successCode,
        msg: msg,
        data: data || null
      };
    };

    ctx.fail = function (data: any,msg: string, code: string | number) {
      ctx.type = option.type || 'json';
      ctx.body = {
        status: "fail",
        code: code || option.failCode,
        msg: msg || option.successMsg,
        data: data || null
      };
    };
    await next();
  };
}
export default routerResponse;
